package com.mimosa.util.config.ini;

import java.util.StringTokenizer;

class Option implements Line {

	private String name;
	private String value;
	private char separator;
	private OptionFormat format;

	private static final String ILLEGAL_VALUE_CHARS = "\n\r";

	public Option(String name, String value, char separator, OptionFormat format) {
		if (!validName(name, separator)) {
			throw new IllegalArgumentException("Illegal option name:" + name);
		}
		this.name = name;
		this.separator = separator;
		this.format = format;
		set(value);
	}

	public String name() {
		return this.name;
	}

	public String value() {
		return this.value;
	}

	public void set(String value) {
		if (value == null) {
			this.value = value;
		} else {
			StringTokenizer st = new StringTokenizer(value.trim(), ILLEGAL_VALUE_CHARS);
			StringBuffer sb = new StringBuffer();
			// XXX this might not be particularly efficient
			while (st.hasMoreTokens()) {
				sb.append(st.nextToken());
			}
			this.value = sb.toString();
		}
	}

	public String toString() {
		return this.format.format(this.name, this.value, this.separator);
	}

	private static boolean validName(String name, char separator) {
		if (name.trim().equals("")) {
			return false;
		}
		if (name.indexOf(separator) >= 0) {
			return false;
		}
		return true;
	}

}